import axios from 'axios'
import app from '../main.js'
import qs from "qs";


/****** 创建axios实例 ******/
const service = axios.create({
  baseURL: "http://127.0.0.1:8081",  // api的base_url
  timeout: 5000  // 请求超时时间
});

var loading;

/****** request拦截器==>对请求参数做处理 ******/
service.interceptors.request.use(config => {

  if (config.url != "/login") {
    config.headers.Authorization = localStorage.getItem("token")
  }
  if (config.url != "/api/qian"){
    config.data = {...config.data};
  }else{
    config.params = {...config.params};
  }

  config.headers['Content-Type'] = 'application/json';
  loading = app.showLoadingDialog("加载中...");
  return config;
}, error => {  //请求错误处理
  loading.close();
  app.alert("error","请求发送错误！")
  Promise.reject(error)
});

/****** respone拦截器==>对响应做处理 ******/
service.interceptors.response.use(
  response => {  //成功请求到数据
    console.log(response.data)
    //这里根据后端提供的数据进行对应的处理

    loading.close();
    if (response.data.code === 0) {
      return response.data;
    } else if(response.data.code === 402){
      app.$router.push({ path:'/login'})
      app.alert("error",response.data.msg)
    }else{
      app.alert("error",response.data.msg)
    }
  },
  error => {  //响应错误处理
    console.log('error');
    console.log(error);
    console.log(JSON.stringify(error));
    loading.close();
    app.alert("error","账号接口异常！请重新登陆！");
    app.$router.push({ path:'/login'});
    return Promise.reject(error)
  }
);

export default service;
